﻿using System.Data;

namespace Citi.GLCosmos.Domain.Utils
{
    public static class Context
    {
        private static GLCosmosEntities instance;
        private static readonly object Padlock = new object();

        /// <summary>
        /// Instancia estática do Contexto de entidades
        /// </summary>
        public static GLCosmosEntities Instance
        {
            get
            {
                lock (Padlock)
                {
                    if (instance == null)
                        instance = new GLCosmosEntities();

                    if (instance.Connection.State == ConnectionState.Broken || instance.Connection.State == ConnectionState.Closed)
                        instance.Connection.Open();

                    return instance;
                }
            }
        }

        public static void SaveChanges()
        {
            try
            {
                Instance.SaveChanges();
            }
            catch (UpdateException)
            {
                throw; 
            }
            catch
            {
                ClearContext();
            }
        }

        public static void ClearAddedInContext()
        {
            var objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Added);

            foreach (var objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
        }

        public static void ClearContext()
        {
            ClearAddedInContext();
            
            var objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
            
            foreach (var objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
            
            objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);
            
            foreach (var objectStateEntry in objectStateEntries)
                Instance.Detach(objectStateEntry.Entity);
        }

        public static void Delete(object entity)
        {
            Instance.DeleteObject(entity);
            SaveChanges();
        }
    }
}
